import Handler from "./Handler"

/** 计时器 */
export default class Timer {

    private _timers: {
        [tickName: string]: {
            time: number,
            end: number
        }
    } = {}

    has(key: string) {
        return this._timers[key] ? true : false
    }

    get(key: string) {
        return this._timers[key]
    }

    set(key: string, time: number, end: number = Date.now() + time) {
        this._timers[key] = { time, end }
    }

    /** 检测是否到达end时间 执行callback(返回超出的时间) */
    check(key: string, callback: (extra: number) => any | Handler<(extra: number) => any>, setEnd?: (time: number, extra: number) => number) {
        let timer = this._timers[key]
        let now = Date.now()
        let extra = now - timer.end
        if (extra >= 0) {
            callback instanceof Handler ? callback.run(extra) : callback(extra)
            if (setEnd) {
                setEnd instanceof Handler ? setEnd.run(timer.time, extra) : setEnd(timer.time, extra)
            } else {
                timer.end = now + timer.time
            }
        }
    }
}